package com.lbd.system.service.impl;

import com.lbd.base.service.BaseServiceImpl;
import com.lbd.system.bean.Authority;
import com.lbd.system.dao.AuthorityRepository;
import com.lbd.system.service.AuthorityService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by WangYajie on 2016/9/19.
 */
@Service
@Transactional
public class AuthorityServiceImpl extends BaseServiceImpl<Authority, AuthorityRepository> implements AuthorityService {
    @Autowired
    AuthorityRepository authorityRepository;

    /**
     * 构建权限查询条件
     *
     * @param authority 条件
     * @param parameter 参数
     * @return
     */
    @Override
    public String buildJpql(Authority authority, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder(" from  Authority t ");
        if (authority != null) {

        }
        return jpqlBuilder.toString();
    }

    /**
     * 通过角色ID查询所拥有权限
     *
     * @param id
     * @return
     */
    @Override
    public List<Authority> findByRoleId(String id) {
        return authorityRepository.findByRoleId(id);
    }

    /**
     * 通过用户ID查询所拥有权限
     *
     * @param id
     * @return
     */
    @Override
    public List<Authority> findByEmpId(String id) {
        return authorityRepository.findByEmpId(id);
    }

    /**
     * 分配权限给角色
     *
     * @param ids 权限ID数组
     * @param rid 角色ID
     */
    @Override
    public void assignToRole(String[] ids, String rid) {
        authorityRepository.deleteByRoleId(rid);
        if (ids != null && StringUtils.isNotBlank(rid)) {
            if (ids.length > 0) {
                for (int i = 0; i < ids.length; i++) {
                    Authority authority = new Authority();
                    authority.setMenuId(ids[i]);
                    authority.setRoleId(rid);
                    authorityRepository.save(authority);
                }
            }
        }
    }

    /**
     * 分配权限给用户
     *
     * @param ids 权限ID数组
     * @param uid 用户ID
     */
    @Override
    public void assignToUser(String[] ids, String uid) {
        authorityRepository.deleteByEmpId(uid);
        if (ids != null && StringUtils.isNotBlank(uid)) {
            if (ids.length > 0) {
                for (int i = 0; i < ids.length; i++) {
                    Authority authority = new Authority();
                    authority.setMenuId(ids[i]);
                    authority.setEmpId(uid);
                    authorityRepository.save(authority);
                }
            }
        }
    }


}
